package com.hh.base.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Properties;

/**
 * 配置文件操作
 */
public class PropertiesUtils {

	public static Properties loadProperties(Class<?> clazz, String name) {
		Properties pro = new Properties();
		InputStream in = null;
		try {
			in = clazz.getResourceAsStream(name);
			pro.load(new BufferedReader(new InputStreamReader(in)));
		} catch (Exception e) {
			// throw new RuntimeException(e);
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (Exception e) {
			}
		}
		return pro;
	}


	/**
	 * 加载带前缀的配置
	 *
	 * @param props  配置文件
	 * @param prefix 前缀
	 * @param out    输出
	 * @param mode   key的类型 0为String 1为Integer
	 * @param <T>    类型,可以为 String 或 Integer
	 */
	public static <T> void loadSubConfig(Properties props, String prefix, Map<T, String> out, int mode) {
		for (Object k : props.keySet()) {
			if (k == null) continue;
			String key = k.toString();

			if (key.startsWith(prefix)) {
				final String pre = key.substring(prefix.length());
				if (mode == 0)
					out.put((T) pre, props.getProperty(key));
				else if (mode == 1) {
					final Integer i = Integer.parseInt(pre);
					out.put((T) i, props.getProperty(key));
				}
				continue;
			}
		}
	}

}
